package com.atguigu.tingshu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private AlbumFeignClient albumFeignClient;

    /**
     * 订单确认数据汇总
     * @param userId 用户id
     * @param tradeVo 选择购买商品交易vo对象
     * @return
     */
    @Override
    public OrderInfoVo tradeData(Long userId, TradeVo tradeVo) {
        //1.初始化orderInfoVo
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        //1.1 初始化相关金额 0.00 此时金额必须是字符串"0.00"
        BigDecimal originalAmount = new BigDecimal("0.00");
        BigDecimal orderAmount = new BigDecimal("0.00");
        BigDecimal derateAmount = new BigDecimal("0.00");

        //1.2. 初始化商品及优惠列表
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        //付款项目类型: 1001-专辑 1002-声音 1003-vip会员
        String itemType = tradeVo.getItemType();
        //2.处理购买商品类型为: vip套餐
        if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(itemType)) {
            //2.1 远程调用"用户"服务获取套餐信息
            VipServiceConfig vipServiceConfig = userFeignClient.getVipServiceConfig(tradeVo.getItemId()).getData();
            Assert.notNull(vipServiceConfig, "选择套餐：{}有误", tradeVo.getItemId());
            //2.2 封装价格: 原价 减免价 订单价
            originalAmount = vipServiceConfig.getPrice();
            orderAmount = vipServiceConfig.getDiscountPrice();
            if (orderAmount.compareTo(originalAmount) != 0) {
                //减免价格 = 原价 - 订单价
                derateAmount = originalAmount.subtract(orderAmount);
            }
            //2.3 封装订单中商品明细列表
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName("会员：" + vipServiceConfig.getName());
            orderDetailVo.setItemPrice(vipServiceConfig.getPrice());
            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
            orderDetailVoList.add(orderDetailVo);
            //2.4 封装商品优惠列表
            if (orderAmount.compareTo(originalAmount) != 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("会员限时优惠：" + derateAmount);
                orderDerateVoList.add(orderDerateVo);
            }
        } else if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(itemType)) {
            //3. 处理购买商品类型为: 专辑
            //3.1 远程调用"用户"服务是否已购专辑
            Long albumId = tradeVo.getItemId();
            Boolean isPaid = userFeignClient.isPaidAlbum(albumId).getData();
            //true:已购买 false:未购买
            if (isPaid) {
                throw new RuntimeException("用户已购买专辑：" + albumId);
            }
            //3.2 远程调用"专辑服务"获取专辑信息
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            Assert.notNull(albumInfo, "专辑：{}不存在", albumId);
            //3.3 远程调用用户服务获取用户身份,封装"商品"相关价格
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
            Boolean isVIP = false;
            if (1 == userInfoVo.getIsVip().intValue() && userInfoVo.getVipExpireTime().after(new Date())) {
                isVIP = true;
            }
            originalAmount = albumInfo.getPrice();
            orderAmount = originalAmount;
            //减免价 = 原价 * 折扣
            if (!isVIP && albumInfo.getDiscount().intValue() != -1) {
                //普通用户 且 专辑有普通用户折扣
                orderAmount = originalAmount.multiply(albumInfo.getDiscount().divide(new BigDecimal("10"),2, RoundingMode.HALF_UP));
            }
            if (isVIP && albumInfo.getVipDiscount().intValue() != -1) {
                //VIP用户 且 专辑有VIP用户折扣
                orderAmount = originalAmount.multiply(albumInfo.getVipDiscount()).divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
            }
            if (orderAmount.compareTo(originalAmount) != 0) {
                derateAmount = originalAmount.subtract(orderAmount);
            }
            //3.4 封装"商品"列表及商品优惠列表
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(albumId);
            orderDetailVo.setItemName("专辑：" + albumInfo.getAlbumTitle());
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVo.setItemPrice(originalAmount);
            orderDetailVoList.add(orderDetailVo);

            if (orderAmount.compareTo(originalAmount) != 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("专辑限时优惠：" + derateAmount);
                orderDerateVoList.add(orderDerateVo);
            }
        } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(itemType)) {
            //4. todo 处理购买商品类型为: 声音
            Long trackId = tradeVo.getItemId();
            Integer trackCount = tradeVo.getTrackCount();
            //4.1 远程调用"专辑服务"获取待购买声音列表
            List<TrackInfo> waitBuyTrackList = albumFeignClient.getWaitBuyTrackList(trackId, trackCount).getData();
            Assert.notNull(waitBuyTrackList, "不存在待结算声音");

            //4.2 远程调用专辑服务得到专辑信息-得到声音单价
            Long albumId = waitBuyTrackList.get(0).getAlbumId();
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            Assert.notNull(albumInfo, "专辑：{}不存在", albumId);

            //4.3 封装"商品"相关价格 声音单价*列表长度 注意：声音不支持折扣
            BigDecimal price = albumInfo.getPrice();
            originalAmount = price.multiply(BigDecimal.valueOf(waitBuyTrackList.size()));
            orderAmount = originalAmount;

            //4.4 封装"商品"列表 将集合泛型从TrackInfo转为OrderDetailVo
            orderDetailVoList = waitBuyTrackList
                    .stream()
                    .map(trackInfo -> {
                        OrderDetailVo orderDetailVo = new OrderDetailVo();
                        orderDetailVo.setItemId(trackInfo.getId());
                        orderDetailVo.setItemName(trackInfo.getTrackTitle());
                        orderDetailVo.setItemUrl(trackInfo.getCoverUrl());
                        orderDetailVo.setItemPrice(price);
                        return orderDetailVo;
                    }).collect(Collectors.toList());
        }
        //5.封装共有订单VO信息: 价格,商品优惠及杂项信息(购买项目类型,流水号,时间戳,签名)
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
        orderInfoVo.setItemType(itemType);
        //5.1 为本次订单产生唯一流水号且存入Reids,将来在提交订单验证流水号
        String tradeNo = IdUtil.randomUUID();
        String tradeKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        redisTemplate.opsForValue().set(tradeKey,tradeNo,RedisConstant.ORDER_TRADE_EXPIRE, TimeUnit.MINUTES);
        orderInfoVo.setTradeNo(tradeNo);
        //5.2 生成时间戳及订单签名
        orderInfoVo.setTimestamp(System.currentTimeMillis());
        //5.2.1 将订单Vo转为Map todo 将付款方式payWay空值属性排除掉,不参与签名计算
        Map<String, Object> orderInfoMap = BeanUtil.beanToMap(orderInfoVo, false, true);
        //5.2.2 调用工具类生成签名值
        String sign = SignHelper.getSign(orderInfoMap);
        orderInfoVo.setSign(sign);

        //6.响应订单vo对象
        return orderInfoVo;
    }

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 订单提交-支付方式选择（1.微信支付 2.余额支付）
     * 核心业务：
     * 1. 保存订单
     * 2. 扣减余额
     * 3. 虚拟物品发货
     *
     * @param userId      用户ID
     * @param orderInfoVo 订单VO信息
     * @return
     */
    @Override
    public Map<String, String> submitOrder(Long userId, OrderInfoVo orderInfoVo) {
        //1.业务校验:验证流水号避免用户利用业务回退导致订单重复提交
        //1.1 确保判断流水号&删除流水号原子性采用Lua脚本执行
        String tradeKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //1.2 创建Lua脚本
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(script, Boolean.class);
        Boolean flag = (Boolean) redisTemplate.execute(redisScript, Arrays.asList(tradeKey, orderInfoVo.getTradeNo()));
        if (!flag) {
            throw new GuiguException(500, "流水号验证失败,请重试");
        }
        //2.业务校验:验证签名是否一致,避免用户篡改订单vo中参数导致商户利益损害
        //2.1 将提交订单的vo转为map用于验证签名
        Map<String, Object> orderInfoMap = BeanUtil.beanToMap(orderInfoVo);
        //2.2 将Map中的payWay属性去除,在订单确认页生成签名没有加入payWay属性
        orderInfoMap.remove("payWay");
        SignHelper.checkSign(orderInfoMap);
        //3.核心业务1: 保存订单相关信息
        //4.判断付款方式-如果是账户余额付款
        //4.1 核心业务2: 余额扣减
        //4.2 核心业务3: 虚拟物品发货
        //5.判断付款方式-如果是微信付款,采用延迟消息完成延迟关单
        return null;
    }
}
